import { reactive, ref } from 'vue'
import {
  NewSaleOrderItemParam,
  NewSaleOrderParam,
  SimpleProductData,
} from '@/api/chunfeng/sale/order/interfaces'
import moment from 'moment'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { useProductApi } from '@/api/chunfeng/product'
import { useSaleOrderApi } from '@/api/chunfeng/sale/order'
import { ProductUnitData } from '@/api/chunfeng/product/interfaces'
import { Form, message } from 'ant-design-vue'

export const useOrderAddFunctions = () => {
  const { executeCommandRequest, executeQueryRequest } = useHttpRequest()

  const { queryProduct, queryProductUnit } = useProductApi()

  const { newSaleOrder } = useSaleOrderApi()

  const csRef = ref()

  const customerIdRef = ref('')
  const newSaleOrderParam = reactive<NewSaleOrderParam>({
    customerId: '',
    occurredAt: moment().format('YYYY-MM-DD'),
    items: [],
  })

  const allProducts = {}
  const productData = ref<Array<SimpleProductData>>([])
  const productUnitData = ref<Array<ProductUnitData>>([])

  const productColumns = [
    {
      title: '商品',
      dataIndex: 'productId',
      key: 'productId',
      slots: { customRender: 'productId' },
    },
    {
      title: '品牌',
      dataIndex: 'brand.name',
      key: 'brandName',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '单位',
      dataIndex: 'unitId',
      key: 'unitId',
      slots: { customRender: 'unitId' },
    },
    {
      title: '价格(元)',
      dataIndex: 'price',
      key: 'price',
      slots: { customRender: 'price' },
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      slots: { customRender: 'quantity' },
    },
    {
      title: '操作',
      key: 'action',
      slots: { customRender: 'action' },
    },
  ]

  const rules = reactive({
    customerId: [
      {
        required: true,
        message: '请选择客户',
      },
    ],
    occurredAt: [
      {
        required: true,
        message: '请选择发生日期',
      },
    ],
  })

  function addNewProductRow() {
    const newProductData: NewSaleOrderItemParam = {
      key: moment().format('x'),
      productId: ' ',
      unitId: '',
      brandName: '',
      price: 0.0,
      quantity: 0.0,
      description: '',
    }
    newSaleOrderParam.items.push(newProductData)
  }

  const { resetFields, validate, validateInfos } = Form.useForm(newSaleOrderParam, rules)
  const layout = {
    labelCol: { span: 24 },
    wrapperCol: { span: 20 },
  }

  function loadProduct() {
    productData.value.length = 0
    executeQueryRequest(queryProduct({ enabled: true }), (result: SimpleProductData[]) => {
      productData.value.push(...result)
      result.forEach((value) => (allProducts[value.uid] = value))
    })
  }

  loadProduct()

  function handleSearch(data: string) {
    console.log(`handleSearch:${data}`)
    // productData.value.length = 0
    // executeQueryRequest(queryProduct({ name: data }), (result: SimpleProductData[]) => {
    //   productData.value.push(...result)
    // })
  }

  function handleChange(productId: string) {
    console.log(`handleChange:${productId}`)
    const item = newSaleOrderParam.items.filter((value) => value.productId === productId)[0]
    item.brand = allProducts[productId].brand
    item.description = allProducts[productId].description

    productUnitData.value.length = 0
    executeQueryRequest(queryProductUnit(productId), (result: ProductUnitData[]) => {
      productUnitData.value.push(...result)
    })
  }

  function add() {
    validate<NewSaleOrderParam>().then((_) => {
      if (!checkOrderItem()) {
        message.info('请完整填写商品信息')
        return
      }
      executeCommandRequest(newSaleOrder(newSaleOrderParam), {
        message: '添加订单成功',
        callback: () => {
          resetFields()
          csRef.value.reset()
        },
      })
    })
  }

  function checkOrderItem(): boolean {
    return (
      newSaleOrderParam.items.length > 0 &&
      newSaleOrderParam.items.every(
        (value) => value.productId && value.quantity > 0 && value.unitId && value.price > 0,
      )
    )
  }

  function customerSelected(customerId: string) {
    customerIdRef.value = customerId
    newSaleOrderParam.customerId = customerId
  }

  function removeItem(key: string) {
    newSaleOrderParam.items = newSaleOrderParam.items.filter((value) => value.key !== key)
  }

  return {
    customerSelected,
    newSaleOrderParam,
    add,
    addNewProductRow,
    handleChange,
    handleSearch,
    layout,
    resetFields,
    validate,
    validateInfos,
    productColumns,
    productData,
    productUnitData,
    removeItem,
    csRef,
  }
}
